package com.itheima.reggie.controller;


import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.itheima.reggie.common.R;
import com.itheima.reggie.constants.AttributeConstant;
import com.itheima.reggie.constants.CommonConstants;
import com.itheima.reggie.dto.LoginQuery;
import com.itheima.reggie.entity.User;
import com.itheima.reggie.enums.HttpEnum;
import com.itheima.reggie.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.RandomStringUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.concurrent.TimeUnit;


/**
 * 用户信息(User)表控制层
 *
 * @author shenjiaqi
 * @since 2024-02-06 09:02:30
 */
@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    /**
     * 服务对象
     */
    @Resource
    private UserService userService;

    /**
     * 短信发送
     *
     * @param user
     * @return
     */
    @PostMapping("/sendMsg")
    public R sendMsg(@RequestBody User user) {
//        String randomNum = RandomStringUtils.randomNumeric(4);
        String randomNum = RandomStringUtils.random(4,
                // 是否为字母
                false,
                // 是否为整数
                true);
        log.info("验证码=============> {}", randomNum);

        stringRedisTemplate.opsForValue()
                .set(CommonConstants.LOGIN_MSG.concat(user.getPhone()), randomNum,
                        // 过期时间两分钟
                        2, TimeUnit.MINUTES);
        return R.success(new HashMap() {{
            put("phone", user.getPhone());
            put("msg", randomNum);
        }});
    }

    /**
     * app登录
     *
     * @param query
     * @return
     */
    @PostMapping("/login")
    public R login(@RequestBody LoginQuery query, HttpSession session) {
        if (null == query || StringUtils.isBlank(query.getCode()) || StringUtils.isBlank(query.getPhone())) {
            return R.error(HttpEnum.PARAMETER_NULL);
        }
        if (Boolean.FALSE.equals(stringRedisTemplate.hasKey(CommonConstants.LOGIN_MSG.concat(query.getPhone())))) {
            return R.error("验证码失效,请重新发送");
        }
        // 缓存验证码
        String cacheCode = stringRedisTemplate.opsForValue().get(CommonConstants.LOGIN_MSG.concat(query.getPhone()));
        if (StringUtils.isBlank(cacheCode)) {
            return R.error("验证码失效,请重新发送");
        }
        if (!StringUtils.equals(cacheCode, query.getCode())) {
            return R.error("验证码错误,请重新输入");
        }

        // 比对成功 查询用户
        User byPhone = userService.getOne(Wrappers.<User>lambdaQuery()
                .eq(User::getPhone, query.getPhone()));
        if (null == byPhone) {
            // 创建新用户
            byPhone = User.builder()
                    .phone(query.getPhone())
                    .status(1)
                    .build();
            userService.save(byPhone);

        }
        Long userId = byPhone.getId();

        // 存入Redis
        stringRedisTemplate.opsForValue().set(CommonConstants.LOGIN_TOKEN.concat(AttributeConstant.ATTRIBUTE_USER), userId.toString(), 30, TimeUnit.MINUTES);
        return R.success("登录成功");
    }
}

